package com.ayu.shortlink.project.mq.consumer;

import com.ayu.shortlink.project.common.cache.CaffeineCacheFactory;
import com.ayu.shortlink.project.common.cache.CommonCacheService;
import com.ayu.shortlink.project.common.constant.RedisKeyConstant;
import com.ayu.shortlink.project.common.constant.RocketMQConstant;
import com.ayu.shortlink.project.mq.basics.base.MessageWrapper;
import com.ayu.shortlink.project.mq.basics.event.HotKeySaveCaffeineEvent;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;

/**
 * hotkey保存到Caffeine的消费者
 */
@Component
@RocketMQMessageListener(
        topic = RocketMQConstant.CACHE_HOTKEY_TOPIC,
        consumerGroup = RocketMQConstant.CACHE_HOTKEY_CONSUMER,
        // Tips：需要进行广播消费
        messageModel = MessageModel.BROADCASTING
)
@Slf4j
public class HotKeySaveToCaffeineConsumer implements RocketMQListener<MessageWrapper<HotKeySaveCaffeineEvent>> {

    // TODO : 添加到本地缓存缓存
    @Override
    public void onMessage(MessageWrapper<HotKeySaveCaffeineEvent> hotKeySaveCaffeineEventMessageWrapper) {
        HotKeySaveCaffeineEvent message = hotKeySaveCaffeineEventMessageWrapper.getMessage();
        CommonCacheService<String, String> shortLinkCache = CaffeineCacheFactory.getShortLinkCache();

        // 构建key
        String key = String.format(RedisKeyConstant.GOTO_SHORT_LINK_KEY, message.getFullShortUrl());
        // 添加
        shortLinkCache.put(key, message.getOriginUrl());
    }
}
